package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import dao.FileDao;
import bean.FileBean;

/**
 * Servlet implementation class UploadFileServlet
 */
public class UploadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadFileServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 //得到上传文件的保存目录 
		String filePath=null;
		String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
		System.out.println(savePath);
		 String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
	     File tmpFile = new File(tempPath);
	     if (!tmpFile.exists()) {
	      //创建临时目录
	      tmpFile.mkdir();
	     }
		File file = new File(savePath);
		System.out.println(savePath);

		if (!file.exists()) {
		System.out.println(savePath+"目录不存在，需要创建");
		
		file.mkdir();
		}
	 
		try{
		
		 DiskFileItemFactory factory = new DiskFileItemFactory();
		 factory.setSizeThreshold(1024*1024*10);//设置缓冲区的大小
	    //设置上传时生成的临时文件的保存目录
	      factory.setRepository(tmpFile);
		  ServletFileUpload upload = new ServletFileUpload(factory);
		
		    upload.setHeaderEncoding("UTF-8"); 
		
	            if(!ServletFileUpload.isMultipartContent(request)){

		        return;
		                 }
		System.out.println("ggggggggggggggggg");
	     //解决上传文件名的中文乱码
	     upload.setHeaderEncoding("UTF-8"); 
	     //3、判断提交上来的数据是否是上传表单的数据
	   
	     System.out.println("hhhhhhhhhhhhhhhhhhhh");
	     upload.setFileSizeMax(1024*1024*1024);
	     //单个文件最大值 
	     upload.setSizeMax(1024*1024*1024);
	     //所有文件最大值 
	     List<FileItem> list = upload.parseRequest(request);
	     FileBean fileBean = null;
	     for(FileItem item : list){
	      // 普通输入框的数据
	    	
	         if(item.isFormField()){
	          String value = item.getString("UTF-8");
	          JSONObject json = JSONObject.fromObject(value);
	          fileBean = new FileBean();
	          fileBean.setUserName(json.getString("userName"));
	          fileBean.setDormitoryId(json.getInt("dormitoryId"));
	          fileBean.setIsSharing(json.getBoolean("isSharing"));
	          
	      System.out.println(value);
	      }else{ 
	        
	       String filename = item.getName(); //上传文件的名称
	       System.out.println(item.getFieldName()); 
	       if(filename==null || filename.trim().equals("")){
	        continue;
	       }  
	       // 获取 文件名 
	       filename = filename.substring(filename.lastIndexOf("\\")+1);
	       System.out.println(filename);
	       //得到上传文件的的名字（不含扩展名）
	       String musicName = filename.split("\\.")[0];
	       System.out.println(musicName);
	       String fileExtName = filename.substring(filename.lastIndexOf("."));
	    
	       System.out.println("上传的文件的扩展名是："+fileExtName);
	       //获取item中的上传文件的输入流
	       InputStream in = item.getInputStream();
	       
	 
	       filePath = makeFileName(musicName);//每首歌创建唯一的文件夹
	       //得到文件的保存目录
	       String realSavePath = makePath(filePath, savePath);
	      
	       //创建一个文件输出流
	     FileOutputStream out = new FileOutputStream(realSavePath + "/" + filename);
	     System.out.print(filePath+fileExtName);
	      
	    /*if(item.getFieldName().equals("ssrc"))
	     {
	    	 song.setSsrc("/upload/"+filePath +"/"+filename);
	    	 System.out.print("数据库存储的路径"+filePath +"/"+filename);
	      }
	    if(item.getFieldName().equals("lyricsrc"))
	    {
	   	 song.setLyricsrc("/upload/"+filePath+"/"+filename);
	   	System.out.print("音乐文件数据库存储的路径"+filePath +"/"+filename);
	     }*/
	       byte buffer[] = new byte[1024*1024]; //创建一个缓冲区
	    	int len = 0;
	   	
	   	while((len=in.read(buffer))>0){
	   	out.write(buffer, 0, len);
	   	}
	   	in.close();
	   	out.close();
	   	item.delete();
	   	fileBean.setFileName(filename);
	   	fileBean.setPath(filePath + "/" + filename);
	   	}
	   	}

		(new FileDao()).insertFile(fileBean);
		response.getWriter().write("true");
		}catch (Exception e) {
	    
	   	e.printStackTrace();

		response.getWriter().write("false");
	   	}
	}

	    private String makeFileName(String musicName){ 
		    
		   return UUID.randomUUID().toString();
		  }  
		   
	    private String makePath(String filename,String savePath){
	    	  
	    	 
	    	   String dir = savePath + "/" + filename; 
	    	 
	    	   File file = new File(dir);
	    	  //如果目录不存在
	    	   if(!file.exists()){
	    	    //创建目录
	    	    file.mkdirs();
	    	  }
	    	   return dir;
	    	  }



}
